@model Material.Mvc.Models.ProductionPlanPagedResult
@{ 
    ViewData["Title"] = "生产计划列表";
    Layout = "_Layout";
}
<link href="~/css/site.css" rel="stylesheet" />
<link href="~/layui/css/layui.css" rel="stylesheet" />

<div class="container mt-4">
    <h2>生产计划列表</h2>
    
    <!-- 查询表单 -->
    <div class="card mb-4">
        <div class="card-header bg-primary text-white">查询条件</div>
        <div class="card-body">
            <form id="searchForm">
                <div class="row g-3"> 
                    <div class="col-md-3"> 
                        <label for="Plan_Number" class="form-label">计划编号</label> 
                        <input type="text" class="form-control" id="Plan_Number" name="Plan_Number" placeholder="请输入计划编号"> 
                    </div> 
                    <div class="col-md-3"> 
                        <label for="Source_Type" class="form-label">来源类型</label> 
                        <input type="text" class="form-control" id="Source_Type" name="Source_Type" placeholder="请输入来源类型"> 
                    </div> 
                    <div class="col-md-3"> 
                        <label for="Product_Name" class="form-label">成品名称</label> 
                        <input type="text" class="form-control" id="Product_Name" name="Product_Name" placeholder="请输入成品名称"> 
                    </div> 
                    <div class="col-md-3"> 
                        <label for="State" class="form-label">状态</label> 
                        <select class="form-select" id="State" name="State"> 
                            <option value="">全部</option> 
                            <option value="0">未开始</option> 
                            <option value="1">进行中</option> 
                            <option value="2">已完成</option> 
                        </select> 
                    </div> 
                    
                    <!-- 操作按钮 --> 
                    <div class="col-md-3 align-self-end"> 
                        <button type="button" class="btn btn-primary me-2" onclick="searchData()">查询</button> 
                        <button type="button" class="btn btn-secondary" onclick="resetForm()">重置</button> 
                    </div> 
                    <input type="hidden" id="PageIndex" name="PageIndex" value="1" /> 
                    <input type="hidden" id="PageSize" name="PageSize" value="10" /> 
                </div>
            </form>
        </div>
    </div>

    <!-- 数据表格 -->
    <div class="card mb-4">
        <div class="card-header bg-info text-white">生产计划列表</div>
        <div class="card-body">
            <div class="mb-3">
                <a href="/Home/ProductionPlan" class="btn btn-success">新增生产计划</a>
            </div>
            
            <!-- 数据表格容器 - 完全由JavaScript填充 -->
            <div id="dataTableContainer">
                <!-- 初始状态显示加载中 -->
                <div class="text-center py-4">
                    <div class="spinner-border" role="status">
                        <span class="sr-only">加载中...</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div id="demo-laypage-all"></div>

<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/layui/layui.js"></script>
<script src="~/js.cookie.js"></script>
<script>
    // 页面加载时执行 - 使用标准的DOMContentLoaded事件
    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById('PageIndex').value = 1; // 重置为第1页
        loadProductionData();
    });

    // 查询数据按钮点击事件
    function searchData() {
        document.getElementById('PageIndex').value = 1; // 重置为第1页
        loadProductionData();
    }

    // 重置表单
    function resetForm() {
        document.querySelector('#searchForm').reset();
        document.getElementById('PageIndex').value = 1;
    }

    // 加载生产计划数据 - 使用外部API版本
    function loadProductionData() {
        // 获取表单数据
        const queryParams = getApiQueryParams();
        
        // 显示加载状态
        document.getElementById('dataTableContainer').innerHTML = '<div class="text-center py-4"><div class="spinner-border" role="status"><span class="sr-only">加载中...</span></div></div>';
        
        // 使用jQuery的get方法
        $.get({
            url: 'http://localhost:5299/api/Plan/GetProduct_PlanShow',
            data: queryParams,  
            dataType: 'json',
            success: function(result) { 
                renderProductionData(result);
            },
            error: function(xhr) {  
                document.getElementById('dataTableContainer').innerHTML =
                    '<div class="text-center text-danger py-4">加载API数据失败，状态码：' + xhr.status + '</div>';
                console.error('加载API数据失败，状态码:', xhr.status);
            }
        });
    }

    // 获取API支持的查询参数
    function getApiQueryParams() {
        // 使用原生JavaScript获取表单数据
        const params = {
            PageIndex: parseInt(document.getElementById('PageIndex').value) || 1,
            PageSize: parseInt(document.getElementById('PageSize').value) || 10,
            Plan_Number: document.getElementById('Plan_Number').value.trim() || undefined,
            Source_Type: document.getElementById('Source_Type').value.trim() || undefined,
            Product_Name: document.getElementById('Product_Name').value.trim() || undefined,
            State: document.getElementById('State').value ? parseInt(document.getElementById('State').value) : undefined
        };
        
        // 过滤掉undefined值，避免不必要的参数传递
        const filteredParams = {};
        for (const key in params) {
            if (params[key] !== undefined && params[key] !== '') {
                filteredParams[key] = params[key];
            }
        }
        
        return filteredParams;
    }

    // 渲染生产计划数据 - 支持API返回格式
    function renderProductionData(data) {
        let tableHtml = '';
        
        // 处理不同格式的返回数据
        let productionData = [];
        
        // 根据API返回值格式，检查pageData数组
        if (data && data.pageData && Array.isArray(data.pageData)) {
            productionData = data.pageData;
        }
        // 检查是否直接返回了数组
        else if (Array.isArray(data)) {
            productionData = data;
        }
        // 检查是否是标准的分页结果格式
        else if (data && data.Items && Array.isArray(data.Items)) {
            productionData = data.Items;
        }
        // 检查是否有其他可能的字段名称
        else if (data && data.data && Array.isArray(data.data)) {
            productionData = data.data;
        }
        
        if (productionData.length > 0) {
            tableHtml += '<table class="table table-bordered table-hover">';
            tableHtml += '<thead class="table-light">';
            tableHtml += '<tr>';
            tableHtml += '<th>计划编号</th>';
            tableHtml += '<th>计划名称</th>';
            tableHtml += '<th>工单数量</th>';
            tableHtml += '<th>来源类型</th>';
            tableHtml += '<th>订单编号</th>';
            tableHtml += '<th>成品名称</th>';
            tableHtml += '<th>成品编号</th>';
            tableHtml += '<th>规格型号</th>';
            tableHtml += '<th>成品类型</th>';
            tableHtml += '<th>计划数量</th>';
            tableHtml += '<th>单位</th>';
            tableHtml += '<th>计划开工</th>';
            tableHtml += '<th>计划完工</th>';
            tableHtml += '<th>需求日期</th>';
            tableHtml += '<th>状态</th>';
            tableHtml += '<th>备注</th>';
            tableHtml += '<th>操作</th>';
            tableHtml += '</tr>';
            tableHtml += '</thead>';
            tableHtml += '<tbody>';
            
            // 遍历数据
            for (let i = 0; i < productionData.length; i++) {
                const item = productionData[i];
                tableHtml += '<tr>';
                tableHtml += '<td>' + (item.plan_Number || item.Plan_Number || '') + '</td>';
                tableHtml += '<td>' + (item.plan_Name || item.Plan_Name || '') + '</td>';
                tableHtml += '<td>' + (item.quantity_Orders || item.Quantity_Orders || 0) + '</td>';
                tableHtml += '<td>' + (item.source_Type || item.Source_Type || '') + '</td>';
                tableHtml += '<td>' + (item.order_Number || item.Order_Number || '') + '</td>';
                tableHtml += '<td>' + (item.product_Name || item.Product_Name || '') + '</td>';
                tableHtml += '<td>' + (item.product_Number || item.Product_Number || '') + '</td>';
                tableHtml += '<td>' + (item.specification || item.Specification || '') + '</td>';
                tableHtml += '<td>' + (item.finished_Type || item.Finished_Type || '') + '</td>';
                tableHtml += '<td>' + (item.planned_quantity || item.Planned_quantity || 0) + '</td>';
                tableHtml += '<td>' + (item.unit || item.Unit || '') + '</td>';
                
                // 日期格式化处理
                let startDate = item.start_Time || item.Start_Time || '';
                if (startDate) {
                    try {
                        startDate = new Date(startDate).toLocaleDateString('zh-CN');
                    } catch (e) {}
                }
                
                let completionDate = item.completion_Time || item.Completion_Time || '';
                if (completionDate) {
                    try {
                        completionDate = new Date(completionDate).toLocaleDateString('zh-CN');
                    } catch (e) {}
                }
                
                let requirementDate = item.requirement_Date || item.Requirement_Date || '';
                if (requirementDate) {
                    try {
                        requirementDate = new Date(requirementDate).toLocaleDateString('zh-CN');
                    } catch (e) {}
                }
                
                tableHtml += '<td>' + startDate + '</td>';
                tableHtml += '<td>' + completionDate + '</td>';
                tableHtml += '<td>' + requirementDate + '</td>';
                
                // 状态显示
                let statusClass = '';
                let statusText = '';
                const stateValue = item.state || item.State;
                switch (stateValue) {
                    case 0:
                        statusClass = 'bg-secondary';
                        statusText = '未开始';
                        break;
                    case 1:
                        statusClass = 'bg-warning';
                        statusText = '进行中';
                        break;
                    case 2:
                        statusClass = 'bg-success';
                        statusText = '已完成';
                        break;
                    default:
                        statusClass = 'bg-info';
                        statusText = '未知';
                }
                tableHtml += '<td><span class="badge ' + statusClass + '">' + statusText + '</span></td>';
                
                tableHtml += '<td>' + (item.notes || item.Notes || '') + '</td>';
                
               tableHtml += '<td>';
                tableHtml += '<a href="/Home/ProductionPlanDetail?id=' + (item.id || item.Id || 0) + '" class="btn btn-primary btn-sm me-1">查看</a>';
                tableHtml += '<button class="btn btn-danger btn-sm" onclick="deletePlan(' + (item.id || item.Id || 0) + ')">删除</button>';
                tableHtml += '</td>';
                tableHtml += '</tr>';
            }
            
            tableHtml += '</tbody>';
            tableHtml += '</table>';
        } else {
            tableHtml += '<div class="text-center text-muted py-4">暂无数据</div>';
        }
        
        document.getElementById('dataTableContainer').innerHTML = tableHtml;
    }

    // 分页跳转
    function gotoPage(pageIndex) {
        document.getElementById('PageIndex').value = pageIndex;
        loadProductionData();
    }

    // 删除计划确认
    function deletePlan(id) {
        if (confirm('确定要删除这条生产计划吗？')) {
            // 实际项目中应调用删除API
            alert('删除功能尚未实现，计划ID：' + id);
        }
    }
</script>

